<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'order:m8OperCheck:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <h3>【订单号：{{ info.ccode }} 图号：{{ info.picno }} 图名：{{ info.picname }}】</h3>
    <BasicForm @register="registerForm" />
    <template #appendFooter>
      <a-button
        :loading="loading"
        v-if="record.checkStatus != 4"
        @click="handleSp()"
        v-auth="'order:m8OperCheck:sp'"
      >
        <Icon icon="simple-line-icons:docs" /> {{ t('保存并审核') }}
      </a-button>
    </template>
    <Modal @register="register" @success="handleSuccess" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsOrderM8OperCheckForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed, h } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { basVenTreeData } from '/@/api/bas/ven/basVen';
  import { M8OperCheck, m8OperCheckSave, m8OperCheckForm } from '/@/api/m8/order/m8OperCheck';
  import { officeTreeData } from '/@/api/sys/office';
  import Modal from './Modal.vue';
  import { useModal } from '/@/components/Modal';
  const [register, { openModal }] = useModal();

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('order.m8OperCheck');
  const { showMessage } = useMessage();
  const record = ref<M8OperCheck>({} as M8OperCheck);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增检验明细') : t('编辑检验明细'),
  }));
  let loading = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('订单编号'),
      field: 'orderId',
      component: 'Input',
      dynamicDisabled: record.value['order.id'] ? true : false,
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('来源ID'),
      field: 'sourceId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('图纸编号'),
      field: 'picId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('流程ID'),
      field: 'flowId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('数铣ID'),
      field: 'sxId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('任务编号'),
      field: 'taskCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('来源工序'),
      field: 'operCode',
      component: 'Input',
      dynamicDisabled: record.value.operCode ? false : true,
      componentProps: {
        maxlength: 64,
      },
      required: true,
      show: false,
    },
    {
      label: t('来源工序'),
      field: 'oper.operName',
      component: 'Input',
      dynamicDisabled: record.value.operCode ? false : true,
      componentProps: {
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('检验类型'),
      field: 'checkType',
      component: 'Select',
      componentProps: {
        dictType: 'm8_check_type',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('工序类型'),
      field: 'operType',
      component: 'Select',
      dynamicDisabled: true,
      componentProps: {
        dictType: 'm8_oper_type',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('检验数量'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('检验备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      suffix: h('button', { class: '', onclick: remarksDate }, '选择'),
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('不合格数量'),
      field: 'bhgQty',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('送检人'),
      field: 'sjManagerCode',
      fieldLabel: 'sjManagerName',
      component: 'TreeSelect',
      componentProps: {
        api: officeTreeData,
        params: { isLoadUser: true, userIdPrefix: '', isAll: true, isShowCode: true },
        immediate: true,
        canSelectParent: false,
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('机床'),
      field: 'machineId',
      fieldLabel: 'machineId',
      component: 'Input',
    },
    // {
    //   label: t('供应商'),
    //   field: 'venCode',
    //   component: 'Select',
    //   componentProps: {
    //     dictType: 'm8_ven',
    //     allowClear: true,
    //   },
    // },
    {
      label: t('供应商'),
      field: 'venCode',
      fieldLabel: 'basVen.name',
      component: 'TreeSelect',
      componentProps: {
        api: basVenTreeData,
        allowClear: true,
      },
    },
    {
      label: t('不合格品处理数量'),
      field: 'dealQty',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      ifShow: record.value.dealQty != 0 ? false : true,
    },
    {
      label: t('材料批号'),
      field: 'orderPic.matPatchNo',
      fieldLabel: 'orderPic.matPatchNo',
      component: 'Input',
      dynamicDisabled: true,
    },
    {
      label: t('实际材料批号'),
      field: 'matPatchNo',
      fieldLabel: 'matPatchNo',
      component: 'Input',
      dynamicDisabled: false,
    },
    {
      label: t('检验员'),
      field: 'checkor.userCode',
      component: 'TreeSelect',
      componentProps: {
        api: officeTreeData,
        params: { isLoadUser: true, userIdPrefix: '', isAll: true, isShowCode: true },
        immediate: true,
        canSelectParent: false,
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('返工数量'),
      field: 'rsQty',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 8,
      },
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('报废数量'),
      field: 'bfQty',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 8,
      },
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('来源类型'),
      field: 'sourceType',
      component: 'Select',
      componentProps: {
        dictType: 'm8_check_source_type ',
        allowClear: true,
      },
      dynamicDisabled: true,
    },
    {
      label: t('状态'),
      field: 'checkStatus',
      component: 'Input',
      componentProps: {},
      show: false,
      dynamicDisabled: true,
    },
    {
      label: t('附件上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'm8OperCheck_file',
        uploadType: 'image',
        maxSize: 100,
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  let info = ref({
    ccode: '',
    picno: '',
    picname: '',
    checkStatus: '',
  });

  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate, updateSchema }] =
    useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    loading.value = true;
    await resetFields();
    const res = await m8OperCheckForm(data);
    record.value = (res.m8OperCheck || {}) as M8OperCheck;
    info.value.ccode = record.value.order.ccode;
    info.value.picno = record.value.orderPic.picno;
    info.value.picname = record.value.orderPic.picname;
    info.value.checkStatus = record.value.checkStatus;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    updateSchema([{ field: 'checkor.userCode', dynamicDisabled: !record.value.canCheck }]);
    loading.value = false;
    setDrawerProps({ loading: false, showOkBtn: record.value.checkStatus == 4 ? false : true });
  });

  function remarksDate() {
    openModal(true, {});
  }
  function handleSuccess(e) {
    let data = getFieldsValue();
    data.remarks = data.remarks ? data.remarks + ',' + e.remarksName : e.remarksName;
    setFieldsValue(data);
  }
  async function handleSubmit() {
    try {
      const data = await validate();
      loading.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djNo: record.value.djNo,
      };
      const res = await m8OperCheckSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loading.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSp() {
    try {
      const data = await validate();
      loading.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djNo: record.value.djNo,
        ope: '4',
      };
      data.ope = '4';
      const res = await m8OperCheckSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loading.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
